import React from 'react'
import { connect } from 'dva';
import {
    Button,
    Table,
    Popconfirm,
    Modal,
    Select,
    Form,
    Input,
    Row,
    Col,
    Upload,
    Icon,
    Progress,
    message,
    Radio,
    DatePicker,
    TreeSelect,
    Checkbox,
    Switch,
} from 'antd';
import './Theme.scss';
import { UrlConfig, getModalList } from '../../../services/fetch';
import { addTheme, themeList, updateTheme, deleteTheme, informationList } from '../../../services/information';
import { getBase64, beforeImgUpload, beforeVideoUpload } from '../../../utils/request';
import { Link } from 'dva/router';
import Qrcode from 'qrcode.react'
import classNames from 'classnames';
const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;
const { Search } = Input;
const { RangePicker } = DatePicker;


@connect(({ add,video }) => ({
    add: add,
    video: video
}))
@Form.create()
export default class Theme extends React.PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            visiblePv: false,
            imageUrl: `${UrlConfig}/application/fcpublic/resource/images/default.png`,
            contentImageUrl: '',
            tmList: [],
            theme_id: '',
            themeList: [],
            pagination: {
                index: 1,
                page_size: 10,
                total: 0
            },
            allData:{}
        }
    }

    componentDidMount() {
        getModalList().then((res) => { //获取样式列表
            if (res.data.code == 200) {
                this.setState({
                    tmList: res.data.data
                })
            }
        })

        this.themeList();
    }

    page = (page, pageSize) => {
        let pagination = this.state.pagination
        pagination.index = page;
        pagination.page_size = pageSize;
        this.setState({ pagination }, () => {
            this.themeList()
        })
    }

    themeList = () => {
        themeList(this.state.pagination).then((res) => {   //获取专题列表
            if (res.data.code == 200) {
                let { pagination } = this.state
                pagination.total = res.data.data.total
                this.setState({
                    themeList: res.data.data.list,
                    pagination: pagination
                })
            }
        })
    }

    showModal = () => {
        this.props.form.resetFields();
        this.setState({
            visible: true,
            theme_id: ''
        })
    }

    showModalEdit = (data) => {
        this.setState({
            visible: true,
            theme_id: data.theme_id,
            imageUrl: data.theme_img,
            contentImageUrl: data.theme_content_img,
        },
        () => {
            const datas = {...data, is_reprint: data.is_reprint === 1 ? true : false}
            this.props.form.setFieldsValue(datas);
        })
    }
    showPvModal = (record) => {
        console.log(record)
        
       this.setState({
           visiblePv:true,
           allData:record
       })

    }

    handlePvCancel = () => {
        this.setState({
            visiblePv:false,
        })
        window.sessionStorage.setItem('scrollY',0)
    }

    showMoreDital = (data) => {
        let urlConfig = UrlConfig;
        let qrUrl = '';
        let qrUrl2 = '';
        let html = '';
            qrUrl = `${urlConfig}/application/fcinformation/mobile/#/List/${data.theme_id}/undefined`;
            qrUrl2 = `${urlConfig}/application/fcinformation/mobile/#/List/${data.theme_id}/undefined?isZixunDetail=1`;
            html = (
                <div>
                    <iframe width="100%" height="600px" src={urlConfig + '/application/fcinformation/mobile/#/List/' + data.theme_id + '/undefined?isZixunDetail=1'}></iframe>

                </div>
            )
      
        let htmlQr = (
            <div>
                {html}
                <div>
                    <b>分享url地址：</b>{qrUrl}
                </div>
                <div>
                    <b>分享二维码：</b><br />{qrUrl ? <Qrcode value={qrUrl} size={120} /> : ''}
                </div>
                <div>
                    <b>预览url地址：</b>{qrUrl2}
                </div>
                <div>
                    <b>预览二维码：</b><br />{qrUrl2 ? <Qrcode value={qrUrl2} size={120} /> : ''}
                </div>
            </div>
        )
        return htmlQr;
    }

    add = () => { //新增专题
        this.props.form.validateFieldsAndScroll((err, val) => {
            val.is_reprint = val.is_reprint ? 1 : 0
            if (!err) {
                if (this.state.theme_id != '') {  //判断是否为编辑
                    val.theme_id = this.state.theme_id
                    updateTheme(val).then((res) => {
                        if (res.data.code == 200) {
                            this.setState({
                                visible: false,
                                imageUrl: "",
                                contentImageUrl: "",
                                percentImage2: 0,
                                percentImage: 0,
                                imgError2: false,
                                imgError1: false
                            })
                            this.themeList();
                            message.success(res.data.msg)
                        }
                    })
                } else {
                    addTheme(val).then((res) => {
                        if (res.data.code == 200) {
                            this.setState({
                                visible: false,
                                imageUrl: "",
                                contentImageUrl: "",
                                percentImage2: 0,
                                percentImage: 0,
                                imgError2: false,
                                imgError1: false
                            })
                            this.themeList();
                            message.success(res.data.msg)
                        }
                    })
                }

            } else {
                message.error('封面图,名称,样式不能为空！');
            }
        })
    }
    /**
     * 图片上传回调
     */
    handleImgChange = (info) => {
        if (info.file.status == 'error') {
            this.setState({ imgError: true });
        }
        if (info.event) {
            this.setState({ percentImage: Math.ceil(info.event.percent) })
        }
        if (info.file.status === 'uploading') {
            this.setState({ loading: true, imgError: false, });
            return;
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj, imageUrl => this.setState({
                imageUrl,
                loading: false,
                imgError: false,
            }));
        }
    }
    /**
     * 图片上传回调
     */
    handleImgChange2 = (info) => {
        if (info.file.status == 'error') {
            this.setState({ imgError2: true });
        }
        if (info.event) {
            this.setState({ percentImage2: Math.ceil(info.event.percent) })
        }
        if (info.file.status === 'uploading') {
            this.setState({ loading2: true, imgError2: false, });
            return;
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj, contentImageUrl => this.setState({
                contentImageUrl,
                loading2: false,
                imgError2: false,
            }));
        }
    }


    delete = (e) => {
        let data = {
            theme_id: e.theme_id
        }
        deleteTheme(data).then((res) => {
            message.success(res.data.msg);
            this.themeList()
        })
    }


    /**
     * 上传插件
     */
    fcUpload = (key) => {
        window.fc = new window.FcUpload({
            elem: 'fcUpload',
            oss: this.props.add.configJson.aliyunOssSwitch,       //是否为oss 上传
            multiple: false,  //是否允许上传多个文件
            type: 'img', // 上传文件类型\ img 图片，  video 视频
            actionImg: `${UrlConfig}/fcpublic/uploads/uploadImg`,  //本地上传图片地址
            actionVideo: `${UrlConfig}/fcpublic/uploads/uploadVideo`,  //本地上传视频地址
            actionOss: this.props.add.configJson.actionOss,  //后端认证接口，获取临时上传凭证
            endpoint: this.props.add.configJson.endpoint,
            bucket: this.props.add.configJson.bucket,
            customDomain : this.props.add.configJson.customDomain,
            ossConfig: this.props.add.configJson,
            callback: (callRes) => {
                let url;
                if (callRes.oss) {  // oss 和本地返回数据结构不一样
                    url = callRes.response[0];
                } else {
                    url = callRes.response[0].data;
                }
                let obj = {}
                obj[key] = url;
                this.props.form.setFieldsValue(obj)
            }
        })

        window.fc.show();
    }


    // 专题 列表搜索
    search = () => {
        const { dispatch, form } = this.props;
        let sorter = this.state.sortInfo;
        form.validateFieldsAndScroll((err, values) => {
            let search = {
                index: 1,
                page_size: 10,
                key:values.key,
                start: values.time ? values.time[0] ? values.time[0].format('YYYY-MM-DD') + " 00:00:00" : '' : '',
                end: values.time ? values.time[1] ? values.time[1].format('YYYY-MM-DD') + " 23:59:59" : '' : '',
            };
            themeList(search).then((res) => {   //获取专题列表
                if (res.data.code == 200) {
                    let { pagination } = this.state
                    pagination.total = res.data.data.total
                    this.setState({
                        themeList: res.data.data.list,
                        pagination: {
                            index: 1,
                            page_size: 10
                        }
                    })
                }
            })

        });
    }

    // 专题 列表搜索
    searchTheme = (value) => {
        let pagination = this.state.pagination
        pagination.key = value
        pagination.index = 1
        themeList(pagination).then((res) => {   //获取专题列表
            if (res.data.code == 200) {
                // let { pagination } = this.state
                pagination.total = res.data.data.total
                this.setState({
                    themeList: res.data.data.list,
                    pagination: pagination
                })
            }
        })
    }
    // 专题 时间 列表 搜索
    changeTime = (date, dateString) => {
        let pagination = this.state.pagination
        if(dateString || dateString.length > 0){
            pagination.start = dateString[0]
            pagination.end = dateString[1]
        }else{
            pagination.start = ''
            pagination.end = ''
        }
        pagination.index = 1
        themeList(pagination).then((res) => {   //获取专题列表
            if (res.data.code == 200) {
                // let { pagination } = this.state
                pagination.total = res.data.data.total
                this.setState({
                    themeList: res.data.data.list,
                    pagination: pagination
                })
            }
        })
    }
    render() {
        const columns = [{
            title: '专题名称',
            className: 'mon_text',
            dataIndex: 'theme_name',
            key: 'theme_name',
            width: 100,
            render: (text, record, index) => {
                return (
                    <Link to={'/ThemeDetail/' + record.theme_id}>
                        {text}
                    </Link>
                )
            }
        }, 
        {
            title: '',
            width: 1,
        }, {
            title: '专题简介',
            className: 'mon_text',
            dataIndex: 'description',
            key: 'description',
        }, {
            title: '创建时间',
            dataIndex: 'create_time',
            key: 'create_time',
            width: 200,
            // sorter: (a, b) => new Date(a.create_time).getTime() - new Date(b.create_time).getTime()
        }, {
            title: '资讯数量',
            dataIndex: 'information_count',
            key: 'information_count',
            width: 120,
            // sorter: (a, b) => a.information_count - b.information_count
        }, {
            title: '操作',
            width: 150,
            render: (text, record, index) => {
                return (
                    <div>
                        <a style={{ marginRight: '10px' }} onClick={() => this.showModalEdit(record)}>修改</a>
                        <a style={{ marginRight: '10px' }} onClick={() => this.showPvModal(record)}>预览</a>
                        <Popconfirm title="确定删除?" icon={null} onConfirm={() => this.delete(record)} okText="确定" cancelText="取消">
                            <a >删除</a>
                        </Popconfirm>
                    </div>
                )
            }
        }];

        const {
            form: { getFieldDecorator },
        } = this.props;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        };
        const uploadButton = () => {
            let text = '点击此处上传';
            if (this.state.loading) {
                text = '上传中...'
            }
            if (this.state.imgError) {
                text = '上传出错,请从新上传';
            }
            return (
                <div>
                    <Icon type={this.state.loading ? 'loading' : 'plus'} />
                    <div className="ant-upload-text">{text}</div>
                </div>
            );
        };
        const uploadButton2 = () => {
            let text = '点击此处上传';
            if (this.state.loading2) {
                text = '上传中...'
            }
            if (this.state.imgError2) {
                text = '上传出错,请从新上传';
            }
            return (
                <div>
                    <Icon type={this.state.loading2 ? 'loading2' : 'plus'} />
                    <div className="ant-upload-text">{text}</div>
                </div>
            );
        };
        const formValue = this.props.form.getFieldsValue();
        return (
            <div className="Theme">
                <section className="Comment" style={{ width: '100%', height: '100%', overflow: 'auto' }}>
                    <header className="header">
                        专题管理
                    </header>
                    <div className="content theme_content">
                        <div className="main">
                            <Row gutter={24}>
                                <Col span={1}>
                                    <Button className='mon_btn' type="defualt" onClick={this.showModal}>ᠲᠤᠰᠭᠠᠢ ᠰᠡᠳᠦᠪ ᠪᠠᠢᠭᠤᠯᠠᠬᠤ</Button>
                                </Col>
                                <Col span={23}>
                                    <div style={{display: 'flex'}}>
                                        <Form layout="inline" onSubmit={this.handleSubmit}>
                                            <FormItem mon_class='mon_label' mon_block='' label='ᠴᠠᠭ' >
                                                <div mon_class='mon_range_picker'>
                                                    {getFieldDecorator('time')(
                                                        <RangePicker placeholder={['ᠡᠬᠢᠯᠡᠬᠦ ᠴᠠᠭ', 'ᠲᠡᠭᠦᠰᠬᠦ ᠴᠠᠭ']} />
                                                    )}
                                                </div>
                                            </FormItem>

                                            <FormItem mon_class='mon_label' mon_block='' label="ᠲᠤᠰᠭᠠᠢ ᠰᠡᠳᠦᠪ᠎ᠦᠨ ᠨᠡᠷ᠎ᠡ">
                                                {getFieldDecorator('key', {
                                                    initialValue: ''
                                                })(
                                                    <Input mon_class='mon_input' className='h_155' placeholder=""/>
                                                )}
                                            </FormItem>

                                            <FormItem>
                                                <Button
                                                    type="primary"
                                                    className='mon_btn ml_10'
                                                    style={{
                                                        marginRight: '20px'
                                                    }}
                                                    onClick={this.search}
                                                >ᠬᠠᠢᠬᠤ</Button>
                                                <Button
                                                    className='mon_btn'
                                                    onClick={() => {
                                                        this.props.form.resetFields();
                                                        this.search()
                                                    }}
                                                >ᠠᠷᠢᠯᠭᠠᠬᠤ</Button>
                                            </FormItem>
                                        </Form>
                                    </div>
                                    <Table
                                        className='mon_table'
                                        dataSource={this.state.themeList}
                                        columns={columns}
                                        pagination={{
                                            total: this.state.pagination.total, //数据总数量
                                            size: 'small',
                                            current: this.state.pagination.index,
                                            showQuickJumper: true,
                                            onChange: (page, pageSize) => {
                                                this.page(page, pageSize)
                                            },
                                            onShowSizeChange: (page, pageSize) => {
                                                this.page(page, pageSize)
                                            },
                                            pageSize: this.state.pagination.page_size,  //显示几条一页
                                            defaultPageSize: this.state.pagination.page_size, //默认显示几条一页
                                            showSizeChanger: true,  //是否显示可以设置几条一页的选项
                                            style: { marginRight: '50px' },
                                            showTotal: (total) => {  //设置显示一共几条数据
                                                return `共有${total}数据`
                                            }
                                        }}
                                    />
                                </Col>
                            </Row>
                        </div>
                    </div>
                </section>
                <Modal
                    title="专题"
                    width={1200}
                    className="theme"
                    visible={this.state.visible}
                    onCancel={() => {
                        this.setState({
                            visible: false
                        })
                    }}
                    onOk={this.add}
                    destroyOnClose
                    footer={[
                        <Button className='mon_btn' onClick={() => {
                            this.setState({
                                visible: false
                            })
                        }}>ᠬᠠᠭᠠᠬᠤ</Button>,
                        <Button className='mon_btn' type="primary" onClick={this.add}>ᠪᠠᠢᠭᠤᠯᠬᠤ</Button>
                    ]}
                >
                    <Form>
                        <FormItem
                            {...formItemLayout}
                            mon_class='mon_label' mon_display='inline'
                            label="ᠲᠤᠰᠭᠠᠢ ᠰᠡᠳᠦᠪ᠎ᠦᠨ ᠨᠡᠷ᠎ᠡ : "
                        >
                            {getFieldDecorator('theme_name', {
                                rules: [{
                                    required: true, message: '请输入专题名称',
                                }],
                            })(
                                <Input mon_class='mon_input' className='h_500' />
                            )}
                        </FormItem>

                        <FormItem
                            {...formItemLayout}
                            mon_class='mon_label'
                            mon_display='inline'
                            label="ᠵᠠᠩᠭᠢᠯᠠᠭ᠎ᠠ᠎ᠶᠢᠨ ᠦᠭᠡ : "
                        >
                            {getFieldDecorator('key_words', {
                                rules: [{
                                    message: '',
                                }],
                            })(
                                <Input mon_class='mon_input' className='mt_20 h_500' />
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            mon_class='mon_label'
                            mon_display='inline'
                            label="ᠲᠣᠪᠴᠢ ᠲᠠᠨᠢᠯᠴᠠᠭᠤᠯᠭ᠎ᠠ : "
                        >
                            <div mon_class='mon_textarea'>
                                {getFieldDecorator('description', {
                                    rules: [{
                                        message: '',
                                    }],
                                })(
                                    <TextArea className='mt_20 h_500' />
                                )}
                            </div>
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            mon_class='mon_label'
                            mon_display='inline'
                            className='ml_40'
                            label="ᠱᠢᠯᠵᠢᠭᠦᠯᠦᠨ ᠨᠡᠢᠲᠡᠯᠡᠬᠦ᠎ᠶᠢ ᠵᠥᠪᠱᠢᠶᠡᠷᠡᠬᠦ : "
                        >
                            {getFieldDecorator('is_reprint', {
                                valuePropName: 'checked'
                            })(
                                <Checkbox ></Checkbox>
                            )}
                        </FormItem>

                        <div mon_class='mon_label' mon_display='inline' className="image ml_10 max_w_350">
                            <div className="title">ᠬᠦᠰᠦᠨᠦᠭ᠎ᠦᠨ ᠭᠠᠳᠠᠷ ᠨᠢᠭᠤᠷ : <span className="red">（根据资讯版面对应样式自定义图片尺寸，并小于2M）</span></div>
                            {getFieldDecorator('theme_img',{
                                initialValue: `${UrlConfig}/application/fcpublic/resource/images/default.png`
                            })(
                                <img onClick={()=>{
                                    this.fcUpload('theme_img')
                                }} src={formValue.theme_img || `${UrlConfig}/application/fcpublic/resource/images/default.png`} className="video_pic" alt="封面图" />
                            )}
                        </div>
                        <div mon_class='mon_label' mon_display='inline' className="image ml_10 max_w_350" style={{ position: 'relative', top: '-25px' }}>
                            <div className="title">ᠠᠭᠤᠯᠭ᠎ᠠ᠎ᠶᠢᠨ ᠭᠠᠳᠠᠷ ᠨᠢᠭᠤᠷ : <span className="red">（根据专题对应样式自定义图片尺寸，并小于2M）</span></div>
                            {getFieldDecorator('theme_content_img',{
                                initialValue: `${UrlConfig}/application/fcpublic/resource/images/default.png`
                            })(
                                <img onClick={()=>{
                                    this.fcUpload('theme_content_img')
                                }} src={formValue.theme_content_img || `${UrlConfig}/application/fcpublic/resource/images/default.png`} className="video_pic" alt="封面图" />
                            )}
                        </div>
                    </Form>
                </Modal>
                {this.state.visiblePv ? <Modal
                    title="预览"
                    visible={this.state.visiblePv}
                    footer={null}
                    onCancel={this.handlePvCancel}
                    width='450px'
                >
                    {this.showMoreDital(this.state.allData)}
                </Modal> : ''}
            </div>
        )
    }
}
